import querystring from 'querystring'
import BaseLayout from '@/views/layout/Base'
import SearchPanel from '@/components/SearchPanel'
import DataTable from '@/components/DataTable'
import {exportExcel} from '@/utils'
import Cookie from 'js-cookie'
// import { getRemind } from '@/api/remind' //TODO ymc在20201209删除旧代码时注释 公共查询消息提醒接口
// import { execlExport } from '@/api/execlExport' //TODO ymc在20201209删除旧代码时注释 公共导出接口
import {
  JobShop,
  CitySelect,
  CityDistrictSelector,
  District,
  CarModel,
  Reception,
  SelectCarModel,
  RoleSelect,
} from '@/components/index' // 导入组件库
export default function ({
  findDataById,
  findData,
  addData,
  updateData,
  deleteData,
  exportData,
  dataName,
  idName,
  format,
  getData,
  isAdd
}) {
  return {
    components: {
      BaseLayout,
      SearchPanel,
      DataTable,
      JobShop,
      CitySelect,
      CityDistrictSelector,
      District,
      CarModel,
      Reception,
      SelectCarModel,
      RoleSelect,
    },
    props: ['id'],
    data() {
      return {
        notQuery: false,
        searchOptions: {},
        pageSize: 10,
        currentPage: 1,
        dialogTitle: '',
        dialogVisible: false,
        tableData: [],
        dialogData: {},
        totalCount: 0,
        buttons: [],
        noFatherId:[],
        interval: function () { }
      }
    },
    async created() { },
    methods: {
      async setTableData() {
        setTimeout(async () => {
          if (!this.notQuery) {
            if (findData) {
              const res = await findData(
                this.searchOptions,
                this.pageSize,
                this.currentPage
              )
              if (dataName[0] === '') {
                this.tableData = res
              } else {
                this.totalCount = parseInt(res.data[dataName[1]])
                console.log(dataName)
                this.tableData =
                  format && Array.isArray(res.data[dataName[0]])
                    ? format(res.data[dataName[0]])
                    : res.data[dataName[0]]
                // this.tableData = [{ depositOrderNo: '张叔叔', status: '未出库', id: 1 }]
              }
            }
          }
          if (isAdd) {
            this.tableData.unshift({ id: '', edit: true })
          }
        }, 100)
        /*
        设置不默认查询notQuery为true， 手动查询修改notQuery为false
        */

      },
      clearSearchOptions() {
        this.searchOptions = {}
      },
      dialogClose() {
        this.dialogVisible = false
        this.dialogTitle = ''
        this.dialogData = {}
      },
      handleDataInsert(title) {
        this.dialogTitle = !title ? '新增' : title
        this.dialogVisible = true
      },
      handleSend() {
        this.dialogTitle = '发送通知'
        this.dialogVisible = true
      },
      async handleDataExport(type,title) {
        exportExcel(type, title,this.searchOptions, this.pageSize, this.currentPage);
        // execlExport(
        //   exportData + '?' + querystring.stringify(this.searchOptions),
        //   title
        // )
      },
      async handleDataChange(row, title) {
        const res = await findDataById(row[idName])
        // const data = getData
        //   ? await getData(res[dataName[1]])
        //   : res[dataName[1]]
        this.dialogTitle = !title ? '查看' : title
        this.dialogVisible = true
        res.data.viewState = true
        this.dialogData = res.data
      },
      async handleDataAfferentChange(row, title) {
        const res = await findDataById(row[idName])
        // const data = getData
        //   ? await getData(res[dataName[1]])
        //   : res[dataName[1]]
        this.dialogTitle = !title ? '修改' : title
        this.dialogVisible = true
        res.data.viewState = false
        this.dialogData = res.data
      },
      async handleDataOperate(data, operate) {
        const { success } =
          operate === 'update' ? await updateData(data) : await addData(data)
        if (success) {
          this.$message({
            message: '操作成功',
            type: 'success'
          })
          this.dialogClose()
          this.setTableData()
        } else {
          this.$message.error('操作失败')
        }
      },
      async handleDataDelete(row, content) {
        var con = !content ? '是否确认删除本条数据?' : content
        this.$confirm(con, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
          const { success } = await deleteData(row[idName])
          if (success) {
            this.$message({
              message: '删除成功',
              type: 'success'
            })
            this.setTableData()
          } else {
            this.$message.error('删除失败')
          }
        })
      },
      handleSizeChange(pageSize) {
        this.pageSize = pageSize
        this.setTableData()
      },
      handleCurrentChange(currentPage) {
        this.currentPage = currentPage
        this.setTableData()
      },
      async handleDataUpdate(row) {
        const { success } =
          row.id === '' ? await addData(row) : await updateData(row)
        if (success) {
          this.$message({
            message: '操作成功',
            type: 'success'
          })
          this.setTableData()
        } else {
          this.$message.error('操作失败')
        }
      }, // 查询提醒消息
      queryReminders() {
        // getRemind().then( remin => {
        //   if(remin.data && remin.data.records){
        //     //通知消息总数
        //     this.$store.state.totalMsg = remin.data.total;
        //     this.$store.state.reminds = [];
        //     var i  = 0;
        //     //头部滚动数据转换
        //     for(let co of remin.data.records){
        //       co.num = i++;
        //       this.$store.state.reminds.push(co);
        //       i++;
        //     }
        //   }
        // })
      },
      /**
       * 关闭当前路由，并返回至前一个或者指定路由
       * @param {*} router
       */
      closeRouter(router = '') {
        this.$store.dispatch('delVisitedViews', this.$route)
        router ? this.$router.push({ path: router }) : history.go(-1)
      },
      filtersFaterId (list) {
        list.map(item => {
          if (item.children && item.children.length > 0) {
            this.filtersFaterId(item.children)
          } else {
            this.noFatherId.push(item.id)
          }
        })
      },
    },
    async mounted() {
      this.queryReminders()
      // 30秒查询一次
      this.interval = setInterval(this.queryReminders, 1000 * 30)
      await this.setTableData()
    },
    created(){
      const token= Cookie.get('x-auth-token')
   if(token){
      this.$store.dispatch('others/setAllStores')   
   }
    },
    destroyed() {
      if (this.interval) {
        clearInterval(this.interval) // 停止
      }
    }
  }
}
